 package com.tinem.platform.web.netty.websocket.message;

 import com.tinem.platform.module.pojo.co.RedisKeyEnum;
 import com.tinem.platform.module.pojo.enums.message.Message;
 import com.tinem.platform.module.starter.jms.consumer.ConsumerService;
 import com.tinem.platform.module.starter.jms.enums.TopicEnum;
 import com.tinem.platform.module.starter.jms.util.impl.JmsTopicUtil;
 import com.tinem.platform.web.netty.websocket.session.Session;
 import io.netty.channel.ChannelHandlerContext;
 import lombok.extern.slf4j.Slf4j;
 import org.springframework.beans.factory.annotation.Value;
 import org.springframework.data.redis.core.StringRedisTemplate;
 import org.springframework.stereotype.Service;

 import javax.annotation.Resource;

 /**
 * @author fengzhihao
 * @version v1
 * @program: platform
 * @className SubscribeCommand
 * @description TODO
 * @site
 * @company
 * @create 2021/12/1 14:24:33
 */
 @Slf4j
@Service("command_close")
public class CloseCommand implements Command {

    @Value("${spring.application.name}")
    protected String name;
    @Value("${spring.profiles.active}")
    protected String active;

    @Resource
    StringRedisTemplate stringRedisTemplate;

    @Resource
    JmsTopicUtil jmsTopicUtil;

     @Resource
     ConsumerService consumerService;

    @Override
    public void call(ChannelHandlerContext ctx, Message message) {
        // 关闭链接
        Session session = Session.getSession(ctx);
        if(session == null){
            return;
        }
        consumerService.cancelSubscribeTopic(session.getConnectionIdSet());
        if(session.getJwt() != null){
            String key = RedisKeyEnum.websocket_user_online.getKey(session.getJwt().getUserId());
            Long sessinNum = stringRedisTemplate.opsForValue().decrement(key);
            log.debug("user online num:({}):({})",sessinNum,RedisKeyEnum.websocket_user_online.getKey(session.getJwt().getUserId()));
            if(sessinNum <= 0){
                //用户下线
                stringRedisTemplate.delete(key);
                log.info("user({}) offline",session.getJwt().getUserId());
                jmsTopicUtil.sendMessage(session.getJwt().getUserId(),name,TopicEnum.WEB_SOCKET_USER_OFFLINE,session.getJwt().getClientId());
            }
        }
        Session.closeSession(session);
    }

}
